#include "../global/global_declarations.h"
#include "stdlib.h"
#include "string.h"
#include "ctype.h"
#include "stdio.h"
#include "../global/misc.h"
#include "../DEHT/deht.h"
#include "../global/global_auth.h"


/**
 * inserts to dest the line that should be written in the file.
 * dest must be large enough to contain the new line.
 */
void process_line(char* line, BasicHashFunctionPtr hash, int hash_length, char* dest) {
	char* word1, *word2;
	int l1;
	char pass[MAX_LINE_LENGTH] = {0};
	word1 = get_word_num_ptr(line, 1, '\t');
	word2 = get_word_num_ptr(line, 2, '\t');
	l1 = get_word_length(word1, '\t');
	get_hexadecimal_hashed_password(word2, hash, pass);
	strncpy(dest, word1, l1);
	dest[l1] = '\t';
	strcpy(dest+l1+1,pass);
	dest[strlen(dest)] = '\n';
}

/**
 * checks the argument given in the command line.
 */
bool check_argv(int n, char* argv[]){
	if (argv == 0 || n != 3){
			fprintf(stderr, "Error: Usage create_authentication <hash function name> <filename to create>\n");
			return false;
		}
		if (!check_Hash_name(argv[1]) || check_file_exist(argv[2]))
			return false;
		return true;
}

int main(int argc, char* argv[]) {
	FILE* f;
	int l;
	BasicHashFunctionPtr hash;
	char file_line[MAX_LINE_LENGTH] = {0};
	char com_line[MAX_LINE_LENGTH] = {0};
	if (!check_argv(argc, argv))
		return 6;
	hash = which_hash(argv[1]);
	l = hash_Length(argv[1]);
	f = fopen(argv[2], "w");
	if (f == NULL){
		perror(argv[2]);
		return 6;
	}
	fprintf(f, "%s\n", argv[1]);
	while (true) {
		printf(">>");
		fgets(com_line, MAX_LINE_LENGTH, stdin);
		remove_end_of_line(com_line);
		if (strcmp(com_line, "quit") == 0)
			break;
		if (strcmp(com_line, "") == 0)
			continue;
		if (count_words_in_line(com_line, '\t') != 2)
			fprintf(stderr, "Error: Commands are either “quit” or <user name>tab<password>.\n");
		else{
			process_line(com_line, hash, l, file_line);
			fwrite(file_line, 1, strlen(file_line), f);
		}
		memset(com_line, 0, MAX_LINE_LENGTH);
		memset(file_line, 0, MAX_LINE_LENGTH);
	}
	fclose(f);
	return 0;
}
